package com.caifu.controller.staff;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.caifu.bean.Result;
import com.caifu.controller.AbstractController;
import com.caifu.excel.ExcelStaffinfo;
import com.caifu.pojo.SysUser;
import com.caifu.pojo.YlStaffInfo;
import com.caifu.service.YlStaffInfoService;
import com.caifu.util.Util;
import com.caifu.vo.YlStaffInfoVo;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 *
 * @author tww
 * ClassName: YlStaffInfoController.java、
 * createTime: 2020年11月09日 10:05:21
 **/
@Controller
@RequestMapping("staff")
public class YlStaffInfoController extends AbstractController {

    private static final Logger logger = LoggerFactory.getLogger(YlStaffInfoController.class);


    @Resource
    private YlStaffInfoService ylStaffInfoService;

    private String prefix = "staff/";

    /**
     * 员工信息页
     */
    @GetMapping("toStaffInfoPage")
    public String toStaffInfoPage() {
        return prefix + "staff_list";
    }

    /**
     * 员工信息列表
     */
    @GetMapping("getStaffInfoList")
    @ResponseBody
    public Result getStaffInfoList(YlStaffInfoVo ylStaffInfoVo) {
        SysUser user = getUser();
        ylStaffInfoVo.setCurrentPensionNo(user.getCurrentPensionNo());
        try {
            PageInfo<YlStaffInfoVo> staffInfoList = ylStaffInfoService.getStaffInfoList(ylStaffInfoVo);
            return success(0, "成功", staffInfoList);
        } catch (Exception e) {
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            logger.error(e.toString());
            e.printStackTrace();
            return error(500, msg);
        }
    }

    /**
     * 员工信息页
     */
    @GetMapping("toStaffInfoAddPage")
    public String toStaffInfoAddPage(String staffNo, Model model) {
        model.addAttribute("staffNo", staffNo);
        return prefix + "staff_add";
    }

    /**
     * 员工添加
     */
    @PostMapping("addStaffInfo")
    @ResponseBody
    public Result addStaffInfo(YlStaffInfo ylStaffInfo) {
        SysUser user = getUser();
        try {
            return ylStaffInfoService.addStaffInfo(ylStaffInfo, user);
        } catch (Exception e) {
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            logger.error(e.toString());
            e.printStackTrace();
            return error(500, msg);
        }
    }

    /**
     * 根据id查询员工信息
     */
    @GetMapping("getStaffInfoById")
    @ResponseBody
    public Result getStaffInfoById(String staffNo) {
        try {
            YlStaffInfo staffInfo = ylStaffInfoService.getStaffInfoById(staffNo);
            return success(200, "success", staffInfo);
        } catch (Exception e) {
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            logger.error(e.toString());
            e.printStackTrace();
            return error(500, msg);
        }
    }

    /**
     * 根据id删除员工信息
     */
    @DeleteMapping("deleteById")
    @ResponseBody
    public Map<String, Object> deleteById(String staffNo) {
        try {
            Map<String, Object> map = ylStaffInfoService.deleteById(staffNo);
            return map;
        } catch (Exception e) {
            String msg = "网络异常";
            if (Util.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            logger.error(e.toString());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 导出员工信息 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("exportExcel")
    public void exportExcel(YlStaffInfoVo ylStaffInfoVo, HttpServletResponse response) throws IOException {
        SysUser user = getUser();
        ylStaffInfoVo.setCurrentPensionNo(user.getCurrentPensionNo());
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = String.valueOf(System.currentTimeMillis());
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelStaffinfo.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("员工信息表")
                    .doWrite(ylStaffInfoService.getExportExcelData(ylStaffInfoVo));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>(10);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
    /**
    * 
    * 功能描述：加密员工导入数据
    *
    * @Author  GZ
    * @Date   2020/12/16 11:38
    */
    @RequestMapping("changeStaffInfo")
    @ResponseBody
    public String changeStaffInfo(){
        try {
            ylStaffInfoService.changeStaffInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
